<?php
Page::$need_view = false;
ini_set('date.timezone', 'Asia/Shanghai');
error_reporting(0);

//file_put_contents(DOXCX_FRAME_PATH.'/log/info/'.date('Y_m_d',time()).'.log', date('H:i:s',time()).':'.json_encode($_POST),FILE_APPEND);
//获取自定义数据
$attach = json_decode($_POST['returnData'], true);
$wid = $attach['wid'];

//支付参数
$payParams = db_query("SELECT * FROM bd_vshop_weixin_pay WHERE wid=?", [$wid])[0];

//将平台公钥转换成正确格式的公钥
$rsaPublicKeyStr = convertRSAKeyStr2Pem($payParams['publicKey']);

//获取签名
$_POST['sign']=$_POST['rsaSign'];
unset($_POST['rsaSign']);

//校验签名
$checkSignRes = checkSignWithRsa($_POST, $rsaPublicKeyStr);
if(!$checkSignRes){
	//file_put_contents(DOXCX_FRAME_PATH.'/log/info/'.date('Y_m_d',time()).'.log', date('H:i:s',time()).'支付回调:签名错误',FILE_APPEND);
	echo json_encode(array("errno"=>1,"msg"=>"签名错误","data"=>array("isConsumed"=>1)));
	exit();
}

switch ($attach['functiontype']){
	case 'notify':
	$m = new Model('vshop_order');
	$m->find(['wid' => $wid, 'OrderNo' => $_POST['tpOrderId']]);//平台订单号
	if ($m->id && $m->PayStatus == 0) {//未支付
        $m->PayStatus = 1;
        $m->tradeNo = $_POST['orderId'];//百度订单号
		$m->BdUserId = $_POST['userId'];
        $m->pay_time = date("Y-m-d H:i:s",$_POST['payTime']);
        $item = json_decode($m->items);
        foreach ($item as $_ite) {
          $pro = new Model('vshop_product');
          $pro->field('id,store_nums,sale_nums,rowtemp')->find($_ite->ProductId);
          if ($pro->id) {
            $store_nums = intval($pro->store_nums) - intval($_ite->Count);
            if ($store_nums <= 0) {
              $store_nums = 0;
            }
            $sale_nums = intval($pro->sale_nums) + intval($_ite->Count);//增加销量
            $rowtemp = getRowtemp($_ite->ProductId, $_ite->goods_no, $_ite->Count);//减少属性里面库存
            $pro->update(['id' => $pro->id], ['store_nums' => $store_nums, 'sale_nums' => $sale_nums, 'rowtemp' => $rowtemp]);
          }
        }
        $rs = $m->save();
        // 打印小票
        try{
          print_shop_order($m->id);
        }catch (Exception $e){}
        // 发送短信
        try{
          $cfg=(new Model('vshop_order_task'))->find(['wid'=>$wid]);
          $pub=(new Model('pubs'))->find(['id'=>$wid]);
          if($cfg->id && $cfg->is_sms_notify==1){
            send_sms($pub->uid, $cfg->sms_notify_phone, '【有用户下单啦，快去看看吧】'.'订单号：'.$m->OrderNo.'；订单金额：'.$m->payAmount);
          }
        }catch (Exception $e){}

        if ($rs->id && $rs->sid) {
          //佣金
          getTypes($rs);
        }
		//返回结果
		echo json_encode(array("errno"=>0,"msg"=>"success","data"=>array("isConsumed"=>2)));
   } else {
       //返回结果
		echo json_encode(array("errno"=>1,"msg"=>"订单找不到或已支付","data"=>array("isConsumed"=>1)));
	}			
    break;  
	case 'groupNotify':
		//找到订单/更新订单
		$order=(new Model('vshop_product_groupbuy_order'))->where(['order_no'=>$_POST['tpOrderId']])->find();
		if($order->id){
			$order->is_pay=1;
			$order->pay_time= time();
			$order->transaction_id=$_POST['orderId'];
			if($order->is_group) {
				$order->group_id = $order->pre_group_id;
			}
			$order->save();
			//找到团，更新人数
			if($order->is_group){
				$group=(new Model('vshop_product_groupbuy_group'))->where(['id'=>$order->group_id])->find();
				$group->curr_num=$group->curr_num+1;
				$group->save();
			}
			//返回结果
			echo json_encode(array("errno"=>0,"msg"=>"success","data"=>array("isConsumed"=>2)));
		}else{
			 //返回结果
			echo json_encode(array("errno"=>1,"msg"=>"订单未找到","data"=>array("isConsumed"=>1)));
		}	
    break;
	case 'MoreshopPayCheapNotify':
		$order=(new Model('moreshop_paycheap_order'))->where(['orderNo'=>$_POST['tpOrderId']])->find();
		if($order->id){
			$order->is_pay=1;
			$order->pay_time=time();
			$order->save();
			//返回结果
			echo json_encode(array("errno"=>0,"msg"=>"success","data"=>array("isConsumed"=>2)));
		}else{
			 //返回结果
			echo json_encode(array("errno"=>1,"msg"=>"订单未找到","data"=>array("isConsumed"=>1)));
		}	
	break;
	case 'moreshopNotify':
		//更新订单
		$order=(new Model('moreshop_sellerin_list'))->where(['orderNo'=>$_POST['tpOrderId']])->find();
		if($order->id){
			$order->is_pay = 1;
			$order->save();
			//创建用户
			$user['username'] = $order->iphone;
			$user['password'] = md5($order->iphone);
			$user['wid'] = $order->wid;
			$user['shopid'] = $order->id;
			(new Model('moreshop_user'))->save($user);
			//返回结果
			echo json_encode(array("errno"=>0,"msg"=>"success","data"=>array("isConsumed"=>2)));
		}else{
			 //返回结果
			echo json_encode(array("errno"=>1,"msg"=>"订单未找到","data"=>array("isConsumed"=>1)));
		}
	break;
	case 'MoreshopPayGoodsNotify':
		//找到订单/更新订单
		$order=(new Model('moreshop_goods_order'))->where(['orderNo'=>$_POST['tpOrderId']])->find();
		if($order->id){
			$order->is_pay=1;
			$order->pay_time=time();
			$order->transaction_id=$_POST['orderId'];
			$order->save();
			//找到商品，更新数量
			$goods=(new Model('moreshop_goods'))->where(['id'=>$order->goodsid])->find();
			$goods->num+=1;
			$goods->save();
			//找到商店，更新总售出数量
			$shop = (new Model('moreshop_sellerin_list'))->where(['id'=>$order->shopid])->find();
			$shop->sell_num+=1;
			$shop->save();
			//返回结果
			echo json_encode(array("errno"=>0,"msg"=>"success","data"=>array("isConsumed"=>2)));
		}else{
			//返回结果
			echo json_encode(array("errno"=>1,"msg"=>"订单未找到","data"=>array("isConsumed"=>1)));
		}
	break;
	case 'seckillNotify':
		//找到订单/更新订单
		$order=(new Model('vshop_product_seckill_order'))->where(['order_no'=>$_POST['tpOrderId']])->find();
		if($order->id){
			$order->is_pay=1;
			$order->pay_time=time();
			$order->transaction_id=$_POST['orderId'];
			$order->save();
			//返回结果
			echo json_encode(array("errno"=>0,"msg"=>"success","data"=>array("isConsumed"=>2)));
		}else{
			//返回结果
			echo json_encode(array("errno"=>1,"msg"=>"订单未找到","data"=>array("isConsumed"=>1)));
		}
	break;
	case 'wxRechargeNotify':
		//找到订单/更新订单
		$log = (new Model('vip_recharge_log'))->find(['out_trade_no' => $_POST['tpOrderId']]);
		if (!$log->transaction_id) {
			$money = $_POST['totalMoney'] / 100;
			// 记录
			$log->transaction_id = $_POST['orderId'];
			$log->total_fee = $money;
			$log->save();
			// 加钱&加积分
			$vipCard = (new Model('vip_card'))->find(['wid' => $wid, 'openid' => $log->openid]);
			$vipSetting = (new Model('vip_setting'))->find(['wid' => $wid]);
			$num = intval($money / $vipSetting->recharge_count);
			$addMoney = $num * $vipSetting->recharge_money;//赠送
			$addPoint = $num * $vipSetting->recharge_point;//赠送
			$totalMoney = $money + $addMoney;
			$vipCard->balance = $vipCard->balance + $totalMoney;
			$vipCard->point = $vipCard->point + $addPoint;
			$vipCard->total_point = $vipCard->total_point + $addPoint;
			$vipCard->save();
			//充值记录
			$rechargeRecord=new Model('vip_recharge_record');
			$rechargeRecord->wid=$wid;
			$rechargeRecord->openid=$log->openid;
			$rechargeRecord->money=$money;
			$rechargeRecord->ctime=time();
			$rechargeRecord->save();
			$tpls = json_decode($vipSetting->tpl_msg, true);
			$tpl = $tpls['tplmsg_recharge'];
			// 通知
			//$send=sendTplMsg_vip_recharge($wid, $tpl, $pay_resp['openid'], $log->form_id, $money, $addMoney, $vipCard->balance, $addPoint, $vipCard->point);
			//返回结果
			echo json_encode(array("errno"=>0,"msg"=>"success","data"=>array("isConsumed"=>2)));
		}
	break;
	case 'payCheapNotify':
		//修改订单信息
		$order=(new Model('vshop_paycheap_order'))->where(['orderNo'=>$_POST['tpOrderId']])->find();
		if($order->id){
			$order->is_pay=1;
			$order->pay_time=time();
			$order->save();
			//返回结果
			echo json_encode(array("errno"=>0,"msg"=>"success","data"=>array("isConsumed"=>2)));
		}else{
			//返回结果
			echo json_encode(array("errno"=>1,"msg"=>"订单未找到","data"=>array("isConsumed"=>1)));
		}
	break;
	case 'bargainNotify':
		//找到订单/更新订单
		$order=(new Model('vshop_goods_bargain_order'))->where(['orderNo'=>$_POST['tpOrderId']])->find();
		if($order->id){
			$order->is_pay=1;
			$order->pay_time=time();
			$order->transaction_id=$_POST['orderId'];
			$order->save();
			//找到商品，更新数量
			$goods=(new Model('vshop_goods_bargain'))->where(['id'=>$order->goodsid])->find();
			$goods->goods_snum=$goods->goods_snum-1;
			$goods->save();
			//返回结果
			echo json_encode(array("errno"=>0,"msg"=>"success","data"=>array("isConsumed"=>2)));
		}else{
			//返回结果
			echo json_encode(array("errno"=>1,"msg"=>"订单未找到","data"=>array("isConsumed"=>1)));
		}
	break;
	case 'tcRechargeNotify':
		//找到订单/更新订单
		$record = (new Model('tc_recharge'))->where(['order_no' => $_POST['tpOrderId']])->find();
		if($record->id){
			$record->is_pay = 1;
			$record->ptime = date('Y-m-d H:i:s');
			$record->save();
			// 给用户增加次数
			$tc_user = (new Model('tc_user'))->find(['wid' => $wid, 'openid' => $record->openid]);
			$tc_user->free_num += $record->num;
			$tc_user->save();
			//返回结果
			echo json_encode(array("errno"=>0,"msg"=>"success","data"=>array("isConsumed"=>2)));
		}else{
			//返回结果
			echo json_encode(array("errno"=>1,"msg"=>"订单未找到","data"=>array("isConsumed"=>1)));
		}
	break;
	case 'tcNotify':
		//找到订单/更新订单
		$msg = (new Model('tc_msg'))->where(['order_no' => $_POST['tpOrderId']])->find();
		if($msg->id){
			$msg->is_pay = 1;
			$msg->top_stime = date('Y-m-d H:i:s');
			$msg->top_etime = date('Y-m-d H:i:s', time() + $msg->top_time * 86400);
			$msg->save();
			//返回结果
			echo json_encode(array("errno"=>0,"msg"=>"success","data"=>array("isConsumed"=>2)));
		}else{
			//返回结果
			echo json_encode(array("errno"=>1,"msg"=>"订单未找到","data"=>array("isConsumed"=>1)));
		}
	break;
	case 'jdNotify':
		//找到订单/更新订单
		$order = (new Model('jd_order'))->where(['order_no' => $_POST['tpOrderId']])->find();
		if($order->id){
			$order->is_pay = 1;
			$order->save();
			// 发送模板消息
			$setting = (new Model('jd_setting'))->find(['wid' => $wid]);
			//sendTplMsg_jd_pay_success($wid, $setting->pay_tplid, $order);
			// 小票打印机
			try {
				print_jd_order($order->id);
			} catch (Exception $e) {

			}
			// 短信通知（商家）
			try {
				$pub = (new Model('pubs'))->find(['id' => $wid]);
				if ($setting->order_notice == 1 && $setting->phone) {
						send_sms($pub->uid, $setting->phone, '酒店有用户支付完成了，快去看看吧！单号' . $order->order_no);
				}
				if ($setting->pay_notice == 1 && $order->phone) {
					send_sms($pub->uid, $order->phone, '您的酒店预订单已经支付成功，订单号：' . $order->order_no);
				}
			} catch (Exception $e) {
				diy_log(['酒店短信发送失败', $e]);
			}
			//返回结果
			echo json_encode(array("errno"=>0,"msg"=>"success","data"=>array("isConsumed"=>2)));
		}else{
			//返回结果
			echo json_encode(array("errno"=>1,"msg"=>"订单未找到","data"=>array("isConsumed"=>1)));
		}
	break;
	case 'zhctNotify':
		//找到订单/更新订单
		$setting = (new Model('zhct_setting'))->find(['wid' => $wid]);
		$order = (new Model('zhct_order'))->where(['order_no' => $_POST['tpOrderId']])->find();
		if($order->id){
			$order->pay_time = date('Y-m-d H:i:s');
			$order->is_pay = 1;
			$order->save();
			// 发送模板消息
			/**if ($setting->template_id) {
				try {
					sendTplMsg_zhct_order_pay_success($wid, $setting->template_id, $openid, $order->form_id, $order->total_price, $order->ctime, $order->pay_time, $order->order_no, $type == 0 ? '点餐' : '外卖', $order->remark ? $order->remark : '无');
				} catch (Exception $e) {
					diy_log(['智慧餐厅模板消息失败', $e]);
				}
			}*/
			// 小票打印机
			try {
				print_zhct_order($order->id);
			} catch (Exception $e) {
				diy_log(['智慧餐厅订单打印失败', $e]);
			}
			// 短信通知
			try {
				if ($setting->tel) {
					$pub = (new Model('pubs'))->find(['id' => $wid]);
					send_sms($pub->uid, $setting->tel, '有用户下单了，快' . ($type == 0 ? '上菜' : '配送') . '吧！单号' . $order->order_no);
				}
			} catch (Exception $e) {
				diy_log(['智慧餐厅短信发送失败', $e]);
			}
			if($order->type==0){
				$table=(new Model('zhct_table'))->find(['wid'=>$wid,'id'=>$order->table_id]);
				$table->status=3;
				$table->save();
			}
			//返回结果
			echo json_encode(array("errno"=>0,"msg"=>"success","data"=>array("isConsumed"=>2)));
		}else{
			//返回结果
			echo json_encode(array("errno"=>1,"msg"=>"订单未找到","data"=>array("isConsumed"=>1)));
		}
	break;
	case 'customFormNotify':
		//找到订单/更新订单
		$log = (new Model('custom_form_data'))->find(['order_no' => $_POST['tpOrderId']]);
		if ($log->id) {
			$log->is_pay = 1;
			$log->save();
			//返回结果
			echo json_encode(array("errno"=>0,"msg"=>"success","data"=>array("isConsumed"=>2)));
		}else{
			//返回结果
			echo json_encode(array("errno"=>1,"msg"=>"订单未找到","data"=>array("isConsumed"=>1)));
		}
	break;
}

	  
  //重置商品属性
   function getRowtemp($id, $goods_no, $Count){
    $arr = [];
    $pro = new Model('vshop_product');
    $pro->field('id,rowtemp')->find($id);
    if ($pro->has_id()) {
      $rowtemp = json_decode($pro->rowtemp);
      $i = 0;
      foreach ($rowtemp as $_v) {
        $arr[$i]['goods_no'] = $_v->goods_no;
        $arr[$i]['spec_array'] = $_v->spec_array;
        if ($_v->store_nums <= 0) {
          $_v->store_nums = 0;
        }
        if ($_v->goods_no == $goods_no) {
          $num = intval($_v->store_nums) - intval($Count);
          if ($num <= 0) {
            $num = 0;
          }
          $arr[$i]['store_nums'] = strval($num);
        } else {
          $arr[$i]['store_nums'] = strval($_v->store_nums);
        }
        $arr[$i]['market_price'] = $_v->market_price;
        $arr[$i]['sell_price'] = $_v->sell_price;
        $arr[$i]['cost_price'] = $_v->cost_price;
        $arr[$i]['weight'] = $_v->weight;
        $i++;
      }
    }
    $arra = json_encode($arr);
    return $arra;
  }
  
  
   //返利佣金
  function getTypes($order){
    $setting = (new Model('vshop_vagent_setting'))->where(['wid' => $order->wid])->find();
    $me = (new Model('vshop_member'))->where(['wxid' => $order->wxid])->find();//下单的用户
    $pm = (new Model('vshop_member'))->where(['id' => $me->pid])->find();//上级用户
    if ($pm->id) {
      //上级返利
      $level1_add = floor($order->payAmount * $setting->level1) / 100;
      $pm->money = $pm->money + $level1_add;
      $pm->unextract_money = $pm->unextract_money + $level1_add;
      $pm->save();
      $blog1 = new Model('vshop_brokerage');
      $blog1->wid = $order->wid;
      $blog1->wxid = $pm->wxid;
      $blog1->orderid = $order->id;
      $blog1->sid = $me->id;
      $blog1->level = 1;
      $blog1->ctime = date('Y-m-d H:i:s');
      $blog1->money = $level1_add;
      $blog1->status = 1;
      $blog1->save();
      $ppm = (new Model('vshop_member'))->where(['id' => $me->pid])->find();//上上级用户
      if ($ppm->id) {
        // 上上级返利
        $level2_add = floor($order->payAmount * $setting->level2) / 100;
        $pm->money = $pm->money + $level2_add;
        $pm->unextract_money = $pm->unextract_money + $level2_add;
        $pm->save();
        $blog2 = new Model('vshop_brokerage');
        $blog2->wid = $order->wid;
        $blog2->wxid = $ppm->wxid;
        $blog2->orderid = $order->id;
        $blog2->sid = $me->id;
        $blog2->level = 2;
        $blog2->ctime = date('Y-m-d H:i:s');
        $blog2->money = $level2_add;
        $blog2->status = 1;
        $blog2->save();
      }
    }
  }
  
 